package org.esk.dablog.web.forms;

import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.validation.BindException;
import org.esk.dablog.service.EntryManager;
import org.esk.dablog.service.UserManager;
import org.esk.dablog.model.Entry;
import org.esk.dablog.model.Picture;
import org.esk.dablog.model.Author;
import org.esk.dablog.web.util.RequestUtils;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Iterator;
import java.util.Date;

/**
 * This class
 * User: jc
 * Date: 22.11.2006
 * Time: 12:32:34
 * $Id:$
 */
public class JoinForm extends SimpleFormController {

    private UserManager userManager;

    public JoinForm() {
        setCommandClass(Author.class);
    }


    public void setUserManager(UserManager userManager) {
        this.userManager = userManager;
    }

    /**
     * processes form submission
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param object
     * @param bindException
     * @return
     * @throws Exception
     */
    protected ModelAndView onSubmit(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object, BindException bindException) throws Exception {
        Author a = (Author) object;
        a.setRegisterDate(new Date());
        userManager.saveAuthor(a);
        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(
                a.getUsername(), a.getPassword()));
        return new ModelAndView(new RedirectView(getSuccessView(), true));
    }


    /**
     * initializes Entry object from request param. redirects to home page in case of errors
     *
     * @param request
     * @return
     * @throws Exception
     */
    protected Object formBackingObject(HttpServletRequest request) throws Exception {
        return new Author();
    }

}
